import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  TextField,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Chip,
  OutlinedInput,
  FormHelperText,
  Grid,
  IconButton,
  Divider,
  CircularProgress,
  Rating,
} from '@mui/material';
import {
  ArrowBack as ArrowBackIcon,
  Add as AddIcon,
  Close as CloseIcon,
} from '@mui/icons-material';
import axios from 'axios';

const KnowledgeForm = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();
  const isEditMode = !!id;

  const [formData, setFormData] = useState({
    title: '',
    content: '',
    category_id: '',
    tags: [],
    attachments: '',
    source: '',
    importance: 0,
  });

  const [categories, setCategories] = useState([]);
  const [allTags, setAllTags] = useState([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [errors, setErrors] = useState({});
  const [attachments, setAttachments] = useState([]);

  useEffect(() => {
    // 获取分类列表
    const fetchCategories = async () => {
      try {
        const response = await axios.get('/api/category?all=true');
        setCategories(response.data);
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    };

    // 获取标签列表
    const fetchTags = async () => {
      try {
        const response = await axios.get('/api/tag');
        setAllTags(response.data);
      } catch (error) {
        console.error('获取标签失败:', error);
      }
    };

    fetchCategories();
    fetchTags();
    
    // 如果不是编辑模式，从URL参数中获取分类ID
    if (!isEditMode) {
      const searchParams = new URLSearchParams(location.search);
      const categoryId = searchParams.get('category_id');
      if (categoryId) {
        setFormData(prev => ({
          ...prev,
          category_id: parseInt(categoryId)
        }));
      }
    }

    // 如果是编辑模式，获取知识条目详情
    if (isEditMode) {
      const fetchKnowledge = async () => {
        setLoading(true);
        try {
          const response = await axios.get(`/api/knowledge/${id}`);
          const knowledge = response.data;
          
          // 转换标签格式
          const tagIds = knowledge.tags ? knowledge.tags.map(tag => tag.id) : [];
          
          // 转换附件格式
          let attachmentList = [];
          if (knowledge.attachments) {
            try {
              attachmentList = JSON.parse(knowledge.attachments);
            } catch (e) {
              console.error('解析附件失败:', e);
            }
          }
          
          setFormData({
            title: knowledge.title || '',
            content: knowledge.content || '',
            category_id: knowledge.category_id || '',
            tags: tagIds,
            attachments: knowledge.attachments || '',
            source: knowledge.source || '',
            importance: knowledge.importance || 0,
          });
          
          setAttachments(attachmentList);
        } catch (error) {
          console.error('获取知识条目失败:', error);
        } finally {
          setLoading(false);
        }
      };

      fetchKnowledge();
    }
  }, [id, isEditMode]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    
    // 清除错误
    if (errors[name]) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };

  const handleTagChange = (event) => {
    const { value } = event.target;
    setFormData(prev => ({
      ...prev,
      tags: value
    }));
  };

  const handleImportanceChange = (event, newValue) => {
    setFormData(prev => ({
      ...prev,
      importance: newValue
    }));
  };

  const handleAddAttachment = () => {
    const newAttachment = { name: '', url: '' };
    setAttachments([...attachments, newAttachment]);
  };

  const handleRemoveAttachment = (index) => {
    const newAttachments = [...attachments];
    newAttachments.splice(index, 1);
    setAttachments(newAttachments);
    
    // 更新formData中的attachments字段
    updateAttachmentsField(newAttachments);
  };

  const handleAttachmentChange = (index, field, value) => {
    const newAttachments = [...attachments];
    newAttachments[index][field] = value;
    setAttachments(newAttachments);
    
    // 更新formData中的attachments字段
    updateAttachmentsField(newAttachments);
  };

  const updateAttachmentsField = (attachmentsList) => {
    setFormData(prev => ({
      ...prev,
      attachments: JSON.stringify(attachmentsList)
    }));
  };

  const validate = () => {
    const newErrors = {};
    
    if (!formData.title.trim()) {
      newErrors.title = '标题不能为空';
    }
    
    if (!formData.category_id) {
      newErrors.category_id = '请选择分类';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!validate()) return;
    
    setSubmitting(true);
    
    try {
      // 更新附件字段
      if (attachments.length > 0) {
        updateAttachmentsField(attachments);
      } else {
        setFormData(prev => ({
          ...prev,
          attachments: ''
        }));
      }
      
      const payload = {
        ...formData,
        tags: formData.tags.map(tagId => parseInt(tagId))
      };
      
      if (isEditMode) {
        // 更新知识条目
        await axios.put(`/api/knowledge/${id}`, payload);
      } else {
        // 创建知识条目
        await axios.post('/api/knowledge', payload);
      }
      
      navigate('/');
    } catch (error) {
      console.error('保存知识条目失败:', error);
      alert('保存失败，请稍后重试');
    } finally {
      setSubmitting(false);
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Box sx={{ mb: 2, display: 'flex', alignItems: 'center' }}>
        <IconButton onClick={handleBack} sx={{ mr: 1 }}>
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h5">
          {isEditMode ? '编辑知识' : '新建知识'}
        </Typography>
      </Box>

      <Paper elevation={1} sx={{ p: 3 }}>
        <Box component="form" onSubmit={handleSubmit}>
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="标题"
                name="title"
                value={formData.title}
                onChange={handleChange}
                error={!!errors.title}
                helperText={errors.title}
                required
              />
            </Grid>
            
            <Grid item xs={12} md={6}>
              <FormControl fullWidth error={!!errors.category_id} required>
                <InputLabel>分类</InputLabel>
                <Select
                  name="category_id"
                  value={formData.category_id}
                  onChange={handleChange}
                  label="分类"
                >
                  {categories.map((category) => (
                    <MenuItem key={category.id} value={category.id}>
                      {category.name}
                    </MenuItem>
                  ))}
                </Select>
                {errors.category_id && <FormHelperText>{errors.category_id}</FormHelperText>}
              </FormControl>
            </Grid>
            
            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel>标签</InputLabel>
                <Select
                  multiple
                  name="tags"
                  value={formData.tags}
                  onChange={handleTagChange}
                  input={<OutlinedInput label="标签" />}
                  renderValue={(selected) => (
                    <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                      {selected.map((value) => {
                        const tag = allTags.find(t => t.id === value);
                        return (
                          <Chip key={value} label={tag ? tag.name : value} />
                        );
                      })}
                    </Box>
                  )}
                >
                  {allTags.map((tag) => (
                    <MenuItem key={tag.id} value={tag.id}>
                      {tag.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="内容"
                name="content"
                value={formData.content}
                onChange={handleChange}
                multiline
                rows={10}
                placeholder="支持Markdown格式..."
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="来源"
                name="source"
                value={formData.source}
                onChange={handleChange}
                placeholder="可选，知识的来源..."
              />
            </Grid>
            
            <Grid item xs={12}>
              <Typography component="legend">重要性</Typography>
              <Rating
                name="importance"
                value={formData.importance}
                onChange={handleImportanceChange}
                max={3}
              />
            </Grid>
            
            <Grid item xs={12}>
              <Typography variant="subtitle1" gutterBottom>
                附件
              </Typography>
              <Box sx={{ mb: 2 }}>
                {attachments.map((attachment, index) => (
                  <Box key={index} sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                    <TextField
                      label="名称"
                      value={attachment.name}
                      onChange={(e) => handleAttachmentChange(index, 'name', e.target.value)}
                      sx={{ mr: 1, flexGrow: 1 }}
                    />
                    <TextField
                      label="URL"
                      value={attachment.url}
                      onChange={(e) => handleAttachmentChange(index, 'url', e.target.value)}
                      sx={{ mr: 1, flexGrow: 2 }}
                    />
                    <IconButton onClick={() => handleRemoveAttachment(index)} color="error">
                      <CloseIcon />
                    </IconButton>
                  </Box>
                ))}
              </Box>
              <Button
                startIcon={<AddIcon />}
                onClick={handleAddAttachment}
                variant="outlined"
                size="small"
              >
                添加附件
              </Button>
            </Grid>
            
            <Grid item xs={12}>
              <Divider sx={{ my: 2 }} />
              <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
                <Button
                  variant="outlined"
                  onClick={handleBack}
                >
                  取消
                </Button>
                <Button
                  type="submit"
                  variant="contained"
                  disabled={submitting}
                >
                  {submitting ? <CircularProgress size={24} /> : '保存'}
                </Button>
              </Box>
            </Grid>
          </Grid>
        </Box>
      </Paper>
    </Box>
  );
};

export default KnowledgeForm;